#include "pch.h"
#include "WebSocket/TcpServer.h"
#include "WebSocket/Thread.h"
#include "WebSocket/TaskList.h"
#include "WebSocket/CpuTimer.h"

using namespace Web;
CpuTimer timer;

float getCurrent()
{
    return timer.currentTime;
}
struct Buffer
{
    int no;
};
struct SeqData
{
    int no;
    float time;
};

struct BufQueue
{
    std::deque<SeqData> dataDeque;
    unsigned long long numHasInsert=0;

    void AddData()
    {
        LOGI("Buf Queue Add data");
        SeqData newData;
        newData.no = numHasInsert++;
        newData.time= getCurrent();

        if(!dataDeque.empty())
        {
            auto head=this->dataDeque[0];
            float time_diff=newData.time-head.time;
            int seq_diff=newData.no -head.no;

            LOGD("Current data time_diff %f seq_diff %d", time_diff, seq_diff);
            
            
            if(getCurrent() - head.time > 1.0f)
            {
                dataDeque.pop_front();
            }
        }

        this->dataDeque.push_back(newData);
    }
};
BufQueue bufQueue;

struct ClientTask:public Web::Thread
{
    TcpClient client;

    void Run()
    {
        while(1)
        {
            Buffer buf;
            int recvlen=client.Recv<Buffer>(buf);
            if(recvlen<=0)
            {
                break;
            }else
            {
                LOGI("recv Buffer %d", buf.no);
                timer.Tick();
                
                LOGI("current Time %f", timer.currentTime);
                bufQueue.AddData();
            }
        }
        LOGI("client disconnected %s %d", client.IP(), client.Port());
        client.Close();

    }
};

int main(int argc, char** argv)
{
    TcpServer::Desc desc;
    TcpServer tcpServer;
    desc.port=1234;
    bool res=tcpServer.Create(desc);
    if(!res)
    {
        LOGI("cannot create file");
        return 0;
    }
    timer.Init();

    LOGD("init cpu Timer");
    
    while(1)
    {
        TcpClient client=tcpServer.Accept();

        LOGI("new client %s %d", client.IP(), client.Port());
        auto tl=TaskList::Get();
        auto newT=tl->CreateThread<ClientTask>();
        newT->client=client;
        newT->Start();
    }
    
    tcpServer.Close();
    LOGI("tcp server closed");
    
};
